﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TYAJZWeb.Models;
using TYAJZWeb.Data;
using TYAJZWeb.Utils;

namespace TYAJZWeb.Controllers
{
    public class DriversController : BaseController
    {
        public ActionResult List(int page)
        {
            var r = Context.Drivers.Where(t => t.IsDeleted == false)
                .OrderByDescending(t => t.Id)
                .Select(t => (DriverListModel)t);
            int totalCount = r.Count();
            r = r.Skip((page - 1) * PAGESIZE).Take(PAGESIZE);
            return View(new PageList<DriverListModel>(r, page, PAGESIZE, totalCount));
        }

        public ActionResult Delete(int id)
        {
            var d = Context.Drivers.Single(t => t.Id == id);
            if (!d.IsWorking)
            {
                d.IsDeleted = true;
                Context.SubmitChanges();
                TempData.Add("Success", "删除成功");
            }
            else
            {
                TempData.Add("Error", "该工人正在操机，不能删除");
            }
            return RedirectToAction("List");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ContentResult Validate(String driverNO, String SingleDriverNO)
        {
            var result = true;
            if (!String.IsNullOrEmpty(driverNO))
            {
                var driver = Context.Drivers.SingleOrDefault(t => t.CertificationNO == driverNO);
                if (driver != null && driver.IsWorking == true)
                {
                    result = false;
                }
            }
            if (!String.IsNullOrEmpty(SingleDriverNO))
            {
                var driver = Context.Drivers.SingleOrDefault(t => t.CertificationNO == SingleDriverNO);
                if (driver != null && driver.IsWorking == true)
                {
                    result = false;
                }
            }

            return new ContentResult() { Content = result.ToString().ToLower() };
        }
    }
}
